document.addEventListener('DOMContentLoaded', () => {
    const extractBtn = document.getElementById('extractBtn');
    const exportBtn = document.getElementById('exportBtn');
    const statusDiv = document.getElementById('status');
    const resultsDiv = document.getElementById('results');

    document.getElementById('captureBtn').addEventListener('click', () => {
        chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
            chrome.tabs.sendMessage(tabs[0].id, { action: 'annotateScreenshot' });
            // chrome.tabs.sendMessage(tabs[0].id, { action: 'getIt' });
        });
    });

    let charPositions = [];

    // 连接到后台脚本
    const port = chrome.runtime.connect();

    // 监听来自后台的消息
    port.onMessage.addListener((msg) => {
        if (msg.positions) {
            statusDiv.innerHTML = `成功获取 ${msg.positions.length} 个字符的位置`;
            charPositions = msg.positions;
            displayResults(charPositions);
        }
    });

    // 提取按钮点击事件
    extractBtn.addEventListener('click', () => {
        // statusDiv.innerHTML = `<span class="loading"></span>正在提取文字位置...`;
        // resultsDiv.innerHTML = '';

        port.postMessage({ action: 'getTextPositions' });
    });

    // 导出按钮点击事件
    exportBtn.addEventListener('click', () => {
        if (charPositions.length === 0) {
            statusDiv.innerHTML = '请先提取文字位置';
            return;
        }

        const dataStr = JSON.stringify(charPositions, null, 2);
        const dataUri = `data:application/json;charset=utf-8,${encodeURIComponent(dataStr)}`;

        const exportFileDefaultName = `text-positions-${new Date().toISOString().slice(0, 10)}.json`;

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();

        statusDiv.innerHTML = `位置数据已导出为JSON文件`;
    });

    // 显示结果
    function displayResults(positions) {
        resultsDiv.innerHTML = '';

        // 只显示前100个结果，避免页面卡顿
        const displayCount = Math.min(100, positions.length);
        const remainingCount = positions.length - displayCount;

        for (let i = 0; i < displayCount; i++) {
            const pos = positions[i];
            const charDiv = document.createElement('div');
            charDiv.className = 'char-info';

            charDiv.innerHTML = `
          <strong>字符:</strong> ${escapeHtml(pos.char)} 
          <div class="position-info">
            <strong>左上角:</strong> (${pos.position.topLeft.x.toFixed(1)}, ${pos.position.topLeft.y.toFixed(1)})
            <strong>右下角:</strong> (${pos.position.bottomRight.x.toFixed(1)}, ${pos.position.bottomRight.y.toFixed(1)})
          </div>
        `;

            resultsDiv.appendChild(charDiv);
        }

        if (remainingCount > 0) {
            const moreInfo = document.createElement('div');
            moreInfo.innerHTML = `<p>还有 ${remainingCount} 个字符未显示...</p>`;
            resultsDiv.appendChild(moreInfo);
        }
    }

    // 转义HTML字符
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
});